package com.cyy.util

import java.io.File
import java.text.DecimalFormat

object FileUtil {
    fun getFileNames(file: File): Array<String?> {
        val returnStrings = arrayOfNulls<String>(2)
        val nameStrings = file.name.split("\\.")
        if (nameStrings.size > 1) {
            val suffixName = nameStrings[nameStrings.size - 1]
            val fileName = file.name.split("\\.$suffixName")[0]
            returnStrings[0] = fileName
            returnStrings[1] = suffixName
        } else {
            returnStrings[0] = file.name
            returnStrings[1] = ""
        }
        return returnStrings
    }

    fun getFileName(file: File): String? {
        return getFileNames(file)[0]
    }

    fun getFileSuffixName(file: File): String? {
//        file.extension
        return getFileNames(file)[1]
    }

    fun getFileSuffixNameAndDot(file: File): String {
        var suffixName = getFileNames(file)[1]
        if ("" != suffixName) {
            suffixName = ".$suffixName"
        }
        return suffixName
    }

    fun getRandomFileName(file: File): String {
        val fileNames = getFileNames(file)
        var fileName = fileNames[0] + ("" + System.currentTimeMillis()).substring(9)
        if ("" != fileNames[1]) {
            fileName += "." + fileNames[1]
        }
        return fileName
    }

    /**
     * 转换文件的大小以B,KB,M,G等计算
     *
     * @param fileS
     * @return
     */
    fun formetFileSize(fileS: Long): String {// 转换文件大小
        val df = DecimalFormat("#.000")
        var fileSizeString = ""
        when {
            fileS < 1024 -> fileSizeString = df.format(fileS.toDouble()) + "B"
            fileS < 1048576 -> fileSizeString = df.format(fileS.toDouble() / 1024) + "K"
            fileS < 1073741824 -> fileSizeString = df.format(fileS.toDouble() / 1048576) + "M"
            else -> fileSizeString = df.format(fileS.toDouble() / 1073741824) + "G"
        }
        return fileSizeString
    }
}